<?php
/**
 * Created by PhpStorm.
 * User: Lzhy ysjywz@gmail.com
 * Date: 2019/8/19
 * Time: 3:13 PM
 */
namespace app\wechat\logic;

use think\Db;

class Tmsg
{
    public static function syncTemplateMsg()
    {
        $res = [];
        $wechatList = Db::table('wechat')->field('id,name,wechat_id')->select();
        foreach ($wechatList as $v){
            try{
                $app = new App($v['id']);
                $weChatInfo = $app->getWeChatInfo();
                $wApp = $app->getApp();
                $data = $wApp->template_message->getPrivateTemplates();
                $_res = ['success'=>0,'msg'=>$data['errmsg'] ?? '查询模板消息失败'];
                if(isset($data['template_list']) && $data['template_list']){
                    $_res = self::_saveOrUpdate($data['template_list'],$weChatInfo);
                }
            }catch (\Exception $e){
                $_res = ['success'=>0,'msg'=>$e->getMessage()];
            }

            if($_res['success']){
                $res['msg'][] = sprintf('公众号「%s」同步完成',$v['name']);
            }else{
                $res['msg'][] = sprintf('公众号「%s」同步失败:%s',$v['name'],$_res['msg']);
            }
        }

        return ['success'=>1,'msg'=>implode('<br>',$res['msg'])];
    }

    public static function _saveOrUpdate($list,$weChatInfo)
    {
        $data = [];
        foreach ($list as $v){
            $v['wechat_id'] = $weChatInfo['wechat_id'];
            $v['update_time'] = date('Y-m-d H:i:s');
            $v['add_time'] = date('Y-m-d H:i:s');
            $data[] = $v;
        }
        
        $res = ['success'=>0,'msg'=>'操作失败,请稍后再试'];
        Db::table('tmsg')->where('wechat_id',$weChatInfo['wechat_id'])->delete();
        if(Db::table('tmsg')->insertAll($data)){
            $res = ['success'=>1,'msg'=>'同步完成'];
        }
        
        return $res;
    }
}